package cn.kgc.shiro01;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.mgt.DefaultSecurityManager;
import org.apache.shiro.subject.Subject;

/**
 * @Author: 课工场
 * @Version: v1.0  2023/7/28
 * @Description:
 */
public class TestAuthorizationInfo {

    public static void main(String[] args) {

        // 1.认证
        DefaultSecurityManager defaultSecurityManager = new DefaultSecurityManager();
        CustomerRealm customerRealm = new CustomerRealm();
        // 创建凭证匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher("MD5");
        hashedCredentialsMatcher.setHashIterations(1024);
        customerRealm.setCredentialsMatcher(hashedCredentialsMatcher);
        defaultSecurityManager.setRealm(customerRealm);

        SecurityUtils.setSecurityManager(defaultSecurityManager);
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken("root", "12345");
        // 没有异常 认证通过
        subject.login(usernamePasswordToken);
        // 判定用户是否认证通过
        boolean authenticated = subject.isAuthenticated();
        System.out.println("authenticated = " + authenticated);

        // 2.访问受限资源    编程式  注解式   调用授权方法
        //boolean b = subject.hasRole("admin");
        //System.out.println("hasRole admin = " + b);

        //boolean[] booleans = subject.hasRoles(Arrays.asList("admin", "customer", "guest"));
        //for (boolean aBoolean : booleans) {
        //    System.out.println("aBoolean = " + aBoolean);
        //}
        //
        //boolean b = subject.hasAllRoles(Arrays.asList("admin", "customer", "guest"));
        //System.out.println("b = " + b);

        //  3. 访问受限资源  通过权限字符串限定的权限    user:add  user:update  user:delete  user:select

        boolean permitted = subject.isPermitted("user:delete");
        System.out.println("permitted = " + permitted);


    }
}
